﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using BarCode.Common;
using BarCode.Bean;

namespace BarCode.Module
{
    public class FileHelper
    {
        private static readonly log4net.ILog LogUtil = log4net.LogManager.GetLogger(typeof(FileHelper));

        /// <summary>
        /// 复制文件
        /// </summary>
        /// <param name="strFrom"></param>
        /// <param name="strTo"></param>
        /// <returns></returns>
        public static int CopyFile(string strFrom, string strTo)
        {
            try
            {
                File.Copy(strFrom, strTo, true);
                LogUtil.Debug("Copy File Successed." + strTo);
            }
            catch (IOException ex)
            {
                LogUtil.Error(ex);
                return Consts.RET_FAIL;
            }
            catch (Exception ex)
            {
                LogUtil.Error(ex);
                return Consts.RET_FAIL;
            }
            return Consts.RET_SUCCESS;
        }

        /// <summary>
        /// 写入文件名
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static int WriteResultFile(GasCodeInfo info)
        {
            try
            {
                string fileName = GlobalVal.csvFilePath + GlobalVal.csvFileName;
                fileName = fileName + "_" + DateTime.Today.ToString("yyyyMMdd") + Consts.FILE_TYPE;

                StringBuilder content = new StringBuilder();
                content.Append(info.body_no);
                content.Append(",");
                content.Append(info.meters_no);
                content.Append(",");
                content.Append(info.did_code);
                content.Append(",");
                content.Append(info.imei_code);
                content.Append(",");
                content.Append(info.iccid_code);
                content.Append(",");
                content.Append(info.Opt_date.ToString("yyyy-MM-dd HH:mm:ss"));
                FileStream fs = new FileStream(fileName, FileMode.Append);
                StreamWriter sw = new StreamWriter(fs);
                //开始写入
                sw.WriteLine(content.ToString());
                //清空缓冲区
                sw.Flush();
                //关闭流
                sw.Close();
                fs.Close();
                LogUtil.Info("写入CSV：" + content.ToString());
            }
            catch (Exception e)
            {
                LogUtil.Error("文件写入失败", e);
                return Consts.RET_FAIL;
            }
            return Consts.RET_SUCCESS;
        }

    }
}
